import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('@/views/DashboardView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/dashboard/map',
        },
        {
          path: 'map',
          name: 'map',
          component: () => import('@/views/MapView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'route-planning',
          name: 'route-planning',
          component: () => import('@/views/guest/RoutePlanningView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'add-facility',
          name: 'add-facility',
          component: () => import('@/views/admin/AddFacilityView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'analytics',
          name: 'analytics',
          component: () => import('@/views/admin/AnalyticsView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'issue-reports',
          name: 'issue-reports',
          component: () => import('@/views/admin/ReviewsReportsView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'maintenance-records',
          name: 'maintenance-records',
          component: () => import('@/views/admin/IssuesRecordsView.vue'),
          meta: { requiresAuth: true },
        },
      ],
    },
  ],
})

// 路由守卫，检查用户是否已登录
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  // 如果路由需要认证且用户未登录，则重定向到登录页面
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})

export default router
